var competitionEntrance = document.querySelector("#competitionEntrance");
var ranking = document.querySelector("#ranking");
var rankList = document.querySelector("#rankList");
var pageInfo = document.querySelector("#pageInfo");
var pageNum = 1;
var pageSize = "";// 总页数
var pastContestList = document.querySelector("#pastContestList");
total = ""; // 总记录数

var now = new Date().getTime();

console.log(customerId);
//竞赛信息模块的渲染
var ajaxContestInfo = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajaxContestInfo.open("GET",ROOTSources+"/contest/getContest",true);
    ajaxContestInfo.send();
    ajaxContestInfo.onreadystatechange=function () {
    if (ajaxContestInfo.readyState ===4){
        if (ajaxContestInfo.status >= 200 && ajaxContestInfo.status<300 || ajaxContestInfo.status===304) {
            var result = JSON.parse(ajaxContestInfo.responseText);
            competitionEntrance.innerHTML =`
             <input type="text" id="hidId" style="display: none" value="${result.data.contestId}">
             <div id="com_Duration">每场竞赛时长为1小时30分钟</div>
             <div id="com_Scene"><h1>${result.data.contestName}</h1></div>
             <div id="com_Date">${dateFormat(result.data.contestStartTime,"-"," ",":")} ~ ${dateFormat(result.data.contestEndTime,"-"," ",":")}</div>
             <div id="com_Day"><img src="${ROOTSources}/images/jkf/day.svg" alt=""><a href="${ROOTSources}/dist/ics/contest.ics" download="hello竞赛" style="color:black;">添加到日程</a></div>
             <div id="com_Timer"><img src="${ROOTSources}/images/jkf/surface.svg">距离开始时间还有：<span id="timer_span"></span></div>
             <div id="com_Into"><a href="${ROOTSources}/contest/goWeekContest/${result.data.contestId}"><img src="${ROOTSources}/images/jkf/getInto.svg" alt=""></a></div>`
            if (now >= new Date(result.data.contestStartTime).getTime()&& now<= new Date(result.data.contestEndTime).getTime()) {
                var newDiv = document.createElement("div");//创建一个div
                newDiv.setAttribute("id","com_Timer");
                var timeDiv = document.querySelector("#com_Timer");
                newDiv.innerHTML=`<img src="${ROOTSources}/images/jkf/surface.svg">比赛正在进行中`;
                competitionEntrance.replaceChild(newDiv,timeDiv);
            }
            else {
                //这是计时器
                var sp=document.querySelector('#timer_span');
                var time_str=result.data.contestStartTime;
                var end_time=new Date(time_str);
                var inter=setInterval(function () {
                    var new_time=new Date();
                    var rtime=end_time-new_time;
                    var f=get(rtime);
                    sp.innerHTML=f;
                },1000);
                //显示的时间样式
                function get(time) {
                    var s=Math.floor((time/1000)%60);
                    // console.log(s);
                    var m=Math.floor((time/1000/60)%60);
                    // console.log(m);
                    var h=Math.floor((time/1000/3600)%24);
                    // console.log(h);
                    var d=Math.floor(time/1000/3600/24)
                    var jieguo=d+'天'+h+'小时'+m+'分钟'+s+'秒';
                    return jieguo;
                }
            }
            //排名模块的渲染
            var hidId=document.querySelector("#hidId");

            var contestId=hidId.value;
            var ajaxContestRank = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
            ajaxContestRank.open("GET",ROOTSources+"/contest/getContestRank/"+contestId,true);
            ajaxContestRank.send();
            ajaxContestRank.onreadystatechange = function () {
                if ( ajaxContestRank.readyState === 4){
                    if (ajaxContestRank.status >= 200 && ajaxContestRank.status<300 || ajaxContestRank.status===304) {
                        var result = JSON.parse(ajaxContestRank.responseText);
                        for (var i = 0;i<result.data.length;i++){
                            rankList.innerHTML +=`
                     <tr>
                        <td class="customerInfo">
                            <span>${result.data[i].customerName}</span>
                        </td>
                        <td class="customerInfoTime">
                            <span>${dateToMinute(result.data[i].contestMsgThroughTime,":")}</span>
                        </td>
                        <td class="customerInfoScores">
                            <span>${result.data[i].contestMsgMark}</span>
                        </td>
                    </tr>
                    `
                        }
                        ranking.innerHTML += `
                <div id="bottom-title">
                    继续努力，争取下一次榜上有名
                </div>`
                    }
                }
            }
        }
    }
 };
    //往期竞赛回顾
ajaxPostFunction();


//把毫秒转化为分钟和秒
function dateToMinute(milliseconds,separator){
    var s=Math.floor((milliseconds/1000)%60);
    // console.log(s);
    var m=Math.floor((milliseconds/1000/60)%60);
    return m+":"+s;
}
//日期转换
function dateFormat(milliseconds,separator1,separator2,separator3) {
    let date = new Date(milliseconds);
    let year = date.getFullYear();
    let month = date.getMonth() +1 ;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    if (month < 10)
        month = "0" +month;
    if (day < 10)
        day = "0" +day;
    if (hours < 10)
        hours = "0" +hours;
    if (minutes < 10)
        minutes = "0" +minutes;
    return year+separator1+month+separator1+day+separator2+hours+separator3+minutes;
}
//分页信息
function pageClick() {
    let previousPageEle = `<li id="previousPageId"><a href="javascript:void 0">&laquo;</a></li>`;
    let nextPageEle = `<li id="nextPageId"><a href="javascript:void 0">&raquo;</a></li>`;
    let content = ``;
    if (pageNum === 1)
        previousPageEle = `<li class="disabled"><a href="javascript:void 0">&laquo;</a></li>`;
    if (pageNum === pageSize)
        nextPageEle = `<li class="disabled"><a href="javascript:void 0">&raquo;</a></li>`;
    for (let i = 0; i < pageSize; i++) {
        if (pageNum === i + 1)
            content += `<li class="green"><a href="javascript:void 0">${i + 1}</a></li>`;
        else
            content += `<li><a href="javascript:void 0">${i + 1}</a></li>`;
    }
    // totalDiv.innerHTML = "共 " + total + " 条数据";
    pageInfo.innerHTML = previousPageEle + content + nextPageEle;
}
/**
 * 分页点谁谁变色
 */
pageInfo.onclick = function () {
    let ele = event.target;
    if (ele.nodeName.toLowerCase() === "a"
        && ele.parentElement.className !== "disabled"
        && ele.parentElement.className !== "green") {
        if (ele.parentElement.id === "previousPageId")
            pageNum--;
        else if (ele.parentElement.id === "nextPageId")
            pageNum++;
        else
            pageNum = parseInt(ele.innerText.trim());
        pageClick(event.target);
        ajaxPostFunction();
    }
};
//往期竞赛渲染
function ajaxPostFunction() {
    var ajaxPastContest = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajaxPastContest.open("GET",ROOTSources+"/contest/getPastContest/"+pageNum,true);
    ajaxPastContest.send();
    ajaxPastContest.onreadystatechange = function () {
        if ( ajaxPastContest.readyState === 4) {
            if (ajaxPastContest.status >= 200 && ajaxPastContest.status < 300 || ajaxPastContest.status === 304) {
                pastContestList.innerHTML = "";
                var result = JSON.parse(ajaxPastContest.responseText);
                pageNum=result.data.pageNum;//当前页码
                pageSize = result.data.pages;
                for (var i=0;i<result.data.list.length;i++){
                    console.log(result.data.list[i].contestId);
                    pastContestList.innerHTML +=`
                     <tr>
                        <td class="table-field contest-title" value="1">
                            <a href="#">
                                <div class="title">${result.data.list[i].contestName}</div>
                                <div class="date">${dateFormat(result.data.list[i].contestStartTime,"-"," ",":")}</div>
                            </a>
                        </td>
                        <td class="table-field contest-duration">
                            <div class="timing" style="overflow: hidden">
                                <div class="begin">
                                    <button class="btn btn-info" onclick=openModal(${result.data.list[i].contestId})>开始</button>
                                </div>
                                1 小时 30 分
                            </div>
                        </td>
                    </tr> `
                }
                pageClick();
            }
        }
    }
}
function  openModal(contestId) {
    document.querySelector("#goGoGo").href=ROOTSources+"/contest/goRunContest/"+contestId+"/"+customerId;
    $("#myModal").modal();
}